package com.pool;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import com.pool.activity.SelectPlayer;
import com.pool.activity.common.FullscreenActivity;
import com.pool.auth.Auth;
import com.pool.common.Strings;
import com.pool.net.Internet;
import com.pool.net.SpreadsheetsConnector;
import com.pool.store.Database;

/**
 * Main entry point. Starts the SelectPlayer activity, where the user can choose the action to
 * execute. When this activity has focus again (meaning back from the SelectPlayer activity), we
 * exit.
 * 
 * @author claveld@gmail.com (David Clavel)
 */
public class AndroidPoolStanding extends FullscreenActivity {

  private static final String CURRENT_USER = "CurrentUser";
  private static final String DATABASE_NAME = "shots";

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    clearSharedPreferences();
    Strings.setApplicationResources(getResources());
    Database.init(getApplicationContext(), DATABASE_NAME);
    Internet.init(getApplicationContext());
    Auth.init(
        getApplicationContext().getSharedPreferences(CURRENT_USER, MODE_PRIVATE),
        SpreadsheetsConnector.get());
    
    Intent intent = new Intent(getApplicationContext(), SelectPlayer.class);
    //Intent intent = new Intent(getApplicationContext(), PointsOverTime.class);
    startActivityForResult(intent, -1);
  }
 
  @Override
  public void onWindowFocusChanged(boolean hasFocus) {
    if (hasFocus) {
      exitApplication();
    }
  }
  
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    exitApplication();
  }
  
  private void exitApplication() {
    clearSharedPreferences();
    Database.get().close();
    finish();    
  }
  
  private void clearSharedPreferences() {
    SharedPreferences.Editor editor = getSharedPreferences(AndroidPoolStanding.CURRENT_USER, MODE_PRIVATE).edit();
    editor.clear();
    editor.commit();
  }
}